package com.dao;

import com.entry.Book;
import com.entry.BorrowInfo;
import com.entry.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * --- Be Humble and Hungry ---
 *
 * @author McMeloxD
 * @date 2024/6/26
 * @desc
 */

public class UserDaoImpl implements UserDao {
    @Override
    public User login(String username, String password) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        User user = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library?useSSL=false&characterEncoding=utf-8", "root", "666888");
            String sql = "select * from user where uname = ? and password = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ps.setString(2, password);

            rs = ps.executeQuery();
            while (rs.next()) {
                user = new User(rs.getInt("uid"), rs.getString("uname"), rs.getString("password"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                ps.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return user;
    }

    @Override
    public boolean register(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library?useSSL=false&characterEncoding=utf-8", "root", "666888");
            String sql = "select * from user where uname = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUname());
            rs = ps.executeQuery();
            if (rs.next()) {
                System.out.println("该账号已经注册过！");
                return false;
            }
            String sql2 = "insert into user(uname,password) values(?,?)";
            ps = conn.prepareStatement(sql2);
            ps.setString(1, user.getUname());
            ps.setString(2, user.getPassword());
            int n = ps.executeUpdate();
            if (n > 0) {
                System.out.println("注册成功");
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                ps.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @Override
    public List<BorrowInfo> borrowInfo(User user) {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        // 先判断当前用户目前是否已经借阅了该书且未归还
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library?useSSL=false&characterEncoding=utf-8", "root", "666888");
            String sql = "select b.bid,b.bname,b.author,b.price,r.btime,if(r.rtime is null,'否','是') '是否归还' from book b,borrow r\n" +
                    "where b.bid = r .bid and uid = ?";
            ps = conn.prepareStatement(sql);
            ps.setInt(1, user.getUid());
            rs = ps.executeQuery();
            ArrayList<BorrowInfo> notRInfo = new ArrayList<>();
            while (rs.next()) {
                notRInfo.add(new BorrowInfo(rs.getInt(1), rs.getString(2), rs.getString(3),
                        rs.getFloat(4), rs.getDate(5), rs.getString(6)));
            }
            // 如果是空集合就说明没这书
            if (notRInfo.isEmpty()) {
                System.out.println("您目前没有来借过图书哦~");
                return null;
            } else {
                // 打印
                System.out.println(user.getUname() + "您好，您在本图书馆借阅的记录为：");
                return notRInfo;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public List<Book> addBook(Book book) {
        // 先查询是否有已存在的图书
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/library?useSSL=false&characterEncoding=utf-8", "root", "666888");
            String sql = "select bname from book where bname = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, book.getBname());
            rs = ps.executeQuery();
            if (rs.next()) {
                if (rs.getString(1).equals(book.getBname())) {
                    System.out.println("亲，图书馆已经有这本书呢！~");
                    return null;
                }
            }
            // 如果不存在就插入
            String sql2 = "insert into book(bname,price,press,author,number) values(?,?,?,?,?)";
            ps = conn.prepareStatement(sql2);
            ps.setString(1, book.getBname());
            ps.setFloat(2, book.getPrice());
            ps.setString(3, book.getPress());
            ps.setString(4, book.getAuthor());
            ps.setInt(5, book.getNumber());
            int n = ps.executeUpdate();
            if (n > 0) {
                System.out.println("添加图书" + book.getBname() + "成功~");
                // 返回最新的图书列表
                String sql3 = "select * from book";
                ps = conn.prepareStatement(sql3);
                rs = ps.executeQuery();
                List<Book> books = new ArrayList<>();
                while (rs.next()) {
                    books.add(new Book(rs.getInt(1), rs.getString(2), rs.getFloat(3), rs.getString(4),
                            rs.getString(5), rs.getInt(6)));
                }
                return books;
            }
        } catch (SQLException e1) {
            e1.printStackTrace();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                rs.close();
                ps.close();
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

